package edu.ustb.controller.orders;

import com.alibaba.fastjson.JSON;
import edu.ustb.domain.orders.Orders;
import edu.ustb.service.order.Impl.OrderServiceImpl;
import edu.ustb.service.order.OrderService;
import edu.ustb.utils.JsonDateValueProcessor;
import edu.ustb.view.JsonData;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

@WebServlet(name = "OrderFindByStaController", value = "/orders/findAllBySta.do")
public class OrderFindByStaController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain;charset=utf-8");

        System.out.println("到达orderfind");
        String userPhone = request.getParameter("phone");
        String orderStatus = request.getParameter("status");
        System.out.println(userPhone);
        OrderService orderService = new OrderServiceImpl();
        //List<Orders> ordersList = orderService.findByPhone(userPhone);
        List<Orders> ordersList = orderService.findBySta(userPhone,orderStatus);
        //
        for(Orders orders:ordersList)
        {
            orders.setOrderDetailList(orderService.findDetailByOrserID(orders.getOrderId()));
            System.out.println("打印多个列表"+orders.getOrderDetailList());
        }
        //处理Java date 格式转换
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        JSONArray jsonArray = JSONArray.fromObject(ordersList,jsonConfig);

        // TODO
        System.out.println("查询成功"+ordersList);

        PrintWriter out = response.getWriter();
        if(ordersList.size()==0)
        {
            JsonData result = JsonData.fail("未找到订单");
            out.write(JSON.toJSONString(result));
            System.out.println("查询地址失败");
            out.flush();
            out.close();
        }
        else
        {
            JsonData result = JsonData.success("订单查询成功",jsonArray);
            out.write(JSON.toJSONString(result));
            System.out.println("查询地址成功");
            out.flush();
            out.close();
        }
    }
}
